package com.example.index.download

import android.util.Log
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import org.greenrobot.eventbus.EventBus
import java.io.File

object FileDownLoadManager {

    val TAG = "FileDownLoadManager"

    //url -> progress
    var downloadProgressMap = hashMapOf<String, Int>()

    //url -> taskid
    var downloadIdMap = hashMapOf<String, Int>()

    // url  -> filename
    var nameMap = hashMapOf<String, String>()

    fun download(url: String, name: String?, dir: String) {

        val id = FileDownloader.getImpl()
            .create(url)
            .setPath(File(dir, name ?: getFileNameWithUrl(url)).absolutePath, false)
            .setCallbackProgressTimes(15)
            .setListener(object : FileDownloadListener() {

                override fun warn(task: BaseDownloadTask) {

                    Log.i(TAG, "warn: ")
                }

                override fun completed(task: BaseDownloadTask) {
                    val event = ProgressEvent(task.url, progress = 100)
                    event.apkFile = File(task.path)
                    EventBus.getDefault().post(event)
                    Log.i(TAG, "completed:${task.path} ${File(task.path).length() / 1024 / 1024} M ")
                }

                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                    Log.i(TAG, "pending: ")
                }

                override fun error(task: BaseDownloadTask, e: Throwable?) {
                    Log.i(TAG, "error: ${e?.message}")
                }

                override fun started(task: BaseDownloadTask) {
                    //下载开始，开始记录 进度
                    downloadProgressMap[url] = 0
                    Log.i(TAG, "started: ${task.filename}")
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    val progress = Math.round(soFarBytes.toFloat() / totalBytes * 100)
                    Log.i(TAG, "progress: $progress")

                    downloadProgressMap[url] = progress
                    EventBus.getDefault().post(ProgressEvent(task.url, progress = progress))
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                    Log.i(TAG, "paused:")
                    val progress = Math.round(soFarBytes.toFloat() / totalBytes * 100)
                    EventBus.getDefault().post(PauseEvent(task.url, progress))
                }

            })
            .start()

        downloadIdMap[url] = id

    }

    private fun getFileNameWithUrl(url: String): String? {
        if (url.endsWith(".apk") && url.lastIndexOf('/') != -1) {
            return url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'))
        }

        //取后五个字符组成的字符串作为 文件名
        return url.substring(url.length - 5, url.length).plus(".apk")
    }


    fun pause(url: String) = FileDownloader.getImpl().pause(downloadIdMap[url]!!)

    fun pause(id: Int) {
        FileDownloader.getImpl()
            .pause(id)
    }

}